"""
@author: zjc
@file: userinfo.py
@time: 2023/3/5 19:30
"""
from model import db
from werkzeug.security import generate_password_hash

class User(db.Model):
    __tablename__ = "userinfo"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(128), nullable=False)
    _password = db.Column("password", db.String(128), nullable=False)
    role = db.Column(db.Integer, default=0)

    def keys(self):
        return ('id', 'username', 'role')

    def __getitem__(self, item):
        return getattr(self, item)

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, value):
        self._password = generate_password_hash(value)

    @classmethod
    def create_user(cls, username, password):
        user = cls()    # 创建实例对象
        user.username = username
        user.password = password
        db.session.add(user)
        db.session.commit()

app_permission=db.Table("app_permission",
                        db.Column("api_id",db.ForeignKey("api_token.id")),
                        db.Column("permission_id",db.ForeignKey("api_permission.id"))
                        )

class ApiToken(db.Model):
    __tablename__="api_token"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    appid = db.Column(db.String(128), nullable=False)
    secretkey= db.Column(db.String(128), nullable=False)
    manage = db.relationship("ApiPermission",secondary=app_permission, backref="token")

    def keys(self):
        return ('id', 'appid', 'secretkey', 'manage')

    def __getitem__(self, item):
        return getattr(self, item)

    @property
    def password(self):
        return self._password_

class ApiPermission(db.Model):
    __tablename__ = "api_permission"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    url = db.Column(db.String(128), nullable=False)
    method_type = db.Column(db.String(128), nullable=False)

    def keys(self):
        return ('id', 'url', 'method_type')

    def __getitem__(self, item):
        return getattr(self, item)

